package mrh.niubi.librarysystem.controller;


import mrh.niubi.librarysystem.common.Result;
import mrh.niubi.librarysystem.constants.Constants;
import mrh.niubi.librarysystem.pojo.Book;
import mrh.niubi.librarysystem.service.AvatarService;
import mrh.niubi.librarysystem.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/book")
@CrossOrigin(origins = "*")
public class BookApplication {

    @Autowired
    private BookService bookService;

    @Autowired
    private AvatarService avatarService;

    @GetMapping("/selectBooksByQueryinf")
    public Result selectBookByQueryinf(@RequestParam String queryinf)  {
        return Result.success(bookService.selectBooksByQueryinf(queryinf));
    }

    @GetMapping("/delBookById")
    public Result delBookById (@RequestParam String id,@RequestParam String imgUrl) {
        if(bookService.delBookById(id) ==1 && avatarService.delete(imgUrl) == 1){
            return Result.success();
        }
        else {
            return Result.error(Constants.CODE_500,"服务器删除失败");
        }
    }

    @PostMapping ("/addBook")
    public Result addBook ( @RequestBody Book book) {
        if(bookService.addBook(book) ==1 && avatarService.add(book.getImgUrl()) == 1){
            return Result.success();
        }
        else {
            return Result.error(Constants.CODE_500,"服务器添加失败");
        }
    }


    @PostMapping("/editBook")
    public Result editBook (@RequestBody Book book) {
        String oldUrl = bookService.selectBookById(book.getId()).getImgUrl();
        if(oldUrl.equals(book.getImgUrl()) && bookService.editBook(book) ==1){
            return Result.success();
        }
        else if(!oldUrl.equals(book.getImgUrl()) && avatarService.delete(oldUrl) == 1  && bookService.editBook(book) == 1  && avatarService.add(book.getImgUrl()) == 1 ){
            return Result.success();
        }
        else {
            return Result.error(Constants.CODE_500,"服务器修改失败");
        }
    }

}
